package cn.kgc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.kgc.base.SystemConstant;
import cn.kgc.entity.Company;
import cn.kgc.entity.Users;
import cn.kgc.excpetion.GraceException;
import cn.kgc.feign.UsersFeignClient;
import cn.kgc.form.CompanyAdminReviewForm;
import cn.kgc.form.CompanyForm;
import cn.kgc.form.CompanyQueryForm;
import cn.kgc.form.CompanyReviewForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.mapper.CompanyMapper;
import cn.kgc.service.CompanyService;
import cn.kgc.utils.PagedGridResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service("companyService")
@SuppressWarnings("all")
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {
    @Resource
    private UsersFeignClient usersFeignClient;


    @Override
    @GlobalTransactional
    public boolean review(CompanyAdminReviewForm companyAdminReviewForm) {
        //无论是否同意,修改审批的状态
        LambdaUpdateWrapper<Company> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(Company::getId,companyAdminReviewForm.getCompanyId());
        updateWrapper.set(Company::getReviewStatus,companyAdminReviewForm.getStatus());
        updateWrapper.set(Company::getReviewReplay,companyAdminReviewForm.getReviewReply());
        update(updateWrapper);
        //如果审批通过,远程修改用户角色
        if(companyAdminReviewForm.getStatus()==SystemConstant.REVIEW_STATUS_PASS){
            Company company= getById(companyAdminReviewForm.getCompanyId());
            //修改用户的角色为HR
            GraceJSONResult graceJSONResult= usersFeignClient.updateUserRole(
                 company.getCommitUserId(),companyAdminReviewForm.getCompanyId()
            );
            //如果远程修改时出现问题,抛出异常 让全局事务回滚。
            if(!(boolean)graceJSONResult.getData() || graceJSONResult.getStatus()!=200){
                GraceException.display(ResponseStatusEnum.USER_ROLE_UPDATE_ERROR);
            }
        }
        return true;
    }

    @Override
    public PagedGridResult queryCompanyList(CompanyQueryForm companyQueryForm) {
        LambdaQueryWrapper<Company> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.likeRight(
                StrUtil.isNotBlank(companyQueryForm.getCompanyName()),
                Company::getCompanyName,
                companyQueryForm.getCompanyName()
        );
        //如果提交人的名字不为空,根据提交人的名字查询提交人的ID,在根据提交人的ID查询。
        if(StrUtil.isNotBlank(companyQueryForm.getCommitName())){
            //获得返回的结果 使用OpenFeign组件时 远程接口调用如果没有使用泛型,返回的结果是LinkedHashMap对象。
            //不能直接将LinkedHashMap对象转为目标类型。
            Object object= usersFeignClient.userIdList(companyQueryForm.getCommitName()).getData();
            //将LinkedHashMap对象转为json字符串
            String jsonStr = JSONUtil.toJsonStr(object);
            //将json字符串转为目标类
            List<Users> users= JSON.parseArray(jsonStr, Users.class);
            List<String> userIds=new ArrayList<>();
            //如果用户名存在,按照用户对应的ID查询
            if(CollUtil.isNotEmpty(users)){
                userIds = users.stream().map(Users::getId).collect(Collectors.toList());
            }else{
                //如果用户名不存在,按照-1用户ID查询。因为表中没有ID为-1的用户,根据ID为-1查询时,应该就不会显示数据了。
                userIds.add("-1");
            }
            queryWrapper.in(Company::getCommitUserId,userIds);
        }
        if(companyQueryForm.getStartDateTime()!=null){
            queryWrapper.ge(Company::getCommitDate,companyQueryForm.getStartDateTime());
        }
        if(companyQueryForm.getEndDateTime()!=null){
            queryWrapper.le(Company::getCommitDate,companyQueryForm.getEndDateTime());
        }
        if(companyQueryForm.getReviewStatus()>=0 && companyQueryForm.getReviewStatus()<=3){
            queryWrapper.eq(Company::getReviewStatus,companyQueryForm.getReviewStatus());
        }
        //分页参数
        Page pageParam=new Page<>(companyQueryForm.getPageIndex(),companyQueryForm.getPageSize());
        //分页+条件 查询
        page(pageParam,queryWrapper);
        //返回查询结果
        return PagedGridResult.setterPagedGrid(pageParam);
    }

    @Override
    public Company goReviewCompany(CompanyReviewForm form) {
        String companyId = form.getCompanyId();
        Company company = getById(companyId);
        //修改公司的审批状态
        company.setReviewStatus(SystemConstant.REVIEW_STATUS_INITIATED);
        company.setCommitUserId(form.getCommitUserId());
        company.setCommitUserMobile(form.getCommitUserMobile());
        company.setAuthLetter(form.getAuthLetter());
        company.setCommitDate(new Date());
        updateById(company);
        //返回公司的信息
        return company;
    }

    @Override
    public Company createCompany(CompanyForm companyForm) {
        Company company=new Company();
        BeanUtil.copyProperties(companyForm,company);
        //公司的审核状态为未发起审批
        company.setReviewStatus(SystemConstant.REVIEW_STATUS_NOT_INITIATED);
        //公司的VIP状态为0
        company.setIsVip(SystemConstant.IS_NOT_VIP);
        save(company);
        return company;
    }

    @Override
    public Company reviewCreateCompany(CompanyForm companyForm) {
        String companyId = companyForm.getCompanyId();
        Company company = getById(companyId);
        //将前面的一些HR审批信息给清空（一次只能有一个用户申请成为公司的HR）
        company.setReviewStatus(SystemConstant.REVIEW_STATUS_NOT_INITIATED);
        company.setReviewReplay("");
        updateById(company);
        return company;
    }

}
